<template>
  <div class="home">
    <div class="top-box">
        <!-- <div class="device">
            <div class="online">
              <p>{{onLine.online_count}}/{{onLine.machine_count}}</p>
              <p>在线设备/总设备</p>
            </div>
            <div>
              <el-progress type="circle" :color="colors2" :percentage="percentage"></el-progress>
            </div>
        </div> -->
        <div class="order">
          <ul class="item" :style="{top:scrollTop+'px'}">
               <li v-for="(item,index) in orderData" :key="index">
                  <el-tooltip class="item"  :content="item.city" placement="top-start" effect="light">
                    <span>{{item.city}}</span>
                  </el-tooltip>
                 <el-tooltip class="item"  :content="item.goods_name" placement="top-start" effect="light">
                    <span>{{item.goods_name}}</span>
                  </el-tooltip>
                  <el-tooltip class="item"  :content="item.pay_type" placement="top-start" effect="light">
                    <span>{{item.pay_type}}</span>
                  </el-tooltip>
                  <el-tooltip class="item"  :content="item.total_fee" placement="top-start" effect="light">
                    <span>￥{{item.total_fee}}</span>
                  </el-tooltip>
                  <el-tooltip class="item"  :content="item.nickname" placement="top-start" effect="light">
                    <span>{{item.nickname}}</span>
                  </el-tooltip>
                  <!-- <el-tooltip class="item"  :content="item.mobile" placement="top-start" effect="light">
                    <span>{{item.mobile}}</span>
                  </el-tooltip> -->
               </li>
            </ul>
          <!-- <vue-seamless-scroll :data="orderData" class="seamless-warp" :class-option="defaultOption" @ScrollEnd='ScrollEnd'>
            <ul class="item">
               <li v-for="(item,index) in orderData" :key="index">
                  <el-tooltip class="item"  :content="item.city" placement="top-start" effect="light">
                    <span>{{item.city}}</span>
                  </el-tooltip>
                 <el-tooltip class="item"  :content="item.goods_name" placement="top-start" effect="light">
                    <span>{{item.goods_name}}</span>
                  </el-tooltip>
                  <el-tooltip class="item"  :content="item.pay_type" placement="top-start" effect="light">
                    <span>{{item.pay_type}}</span>
                  </el-tooltip>
                  <el-tooltip class="item"  :content="item.total_fee" placement="top-start" effect="light">
                    <span>￥{{item.total_fee}}</span>
                  </el-tooltip>
                  <el-tooltip class="item"  :content="item.nickname" placement="top-start" effect="light">
                    <span>{{item.nickname}}</span>
                  </el-tooltip>
                  <el-tooltip class="item"  :content="item.mobile" placement="top-start" effect="light">
                    <span>{{item.mobile}}</span>
                  </el-tooltip>
               </li>
            </ul>
          </vue-seamless-scroll> -->
        </div>
    </div>
    <div style="width:100%;height:100vh;" v-if="regData.length>0">
      <MyMaps :renderData='renderMapData' :renderData2='renderMapData2' :regData='regData'></MyMaps>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
// import HelloWorld from '@/components/HelloWorld.vue'
import ReconnectingWebSocket from 'reconnecting-websocket'
import MyMaps from '../components/map/index'
import { clearInterval } from 'timers'
export default {
  name: 'home',
  data () {
    return {
      scrollTop: 0,
      renderMapData: [],
      renderMapData2: [],
      regData: [],
      orderData: [],
      onLine: {
        online_count: 0,
        machine_count: 0
      },
      percentage: 0,
      colors2: [
        { color: '#e40028', percentage: 20 },
        { color: '#e2473f', percentage: 40 },
        { color: '#ff686b', percentage: 60 },
        { color: '#72b585', percentage: 80 },
        { color: '#23ce6b', percentage: 100 }
      ],
      mapIndex: 0,
      timer: null,
      // path: 'ws://192.168.124.5:9501', // http://192.168.124.5: ws://www.zgweiqu.com:9501
      path: 'ws://www.zgweiqu.com:9501', // ws://www.zgweiqu.com:9501
      is_first: 1,
      socket: null,
      socketData: [],
      orderTimer: null
    }
  },
  mounted () {
    this.getRegion()
    this.getOrder()
    // this.getOnline()
    this.initSocket()
    // setInterval(() => {
    this.send()
    // 初始化 TweenJs 监听
    this.tweenAni()
    // }, 90000)
  },
  methods: {
    getRegion () {
      let params = `timestamp=${Date.parse(new Date())}`
      this.$getCode(params).then(code => {
        this.http.getMainRegion(code).then(res => {
          if (res.data.errno == '000') {
            // console.log('renderMapData', res)
            // this.renderMapData = res.data.result.data
            res.data.result.data.forEach(element => {
              // console.log('element', element)
              this.regData.push({
                name: element.name,
                value: [element.longitude, element.latitude, 2000]
                // longitude: element.longitude,
                // latitude: element.latitude,
                // value: 32358260,
                // color: '#0394d9'
              })
            })
          } else {
            this.$message.error(res.data.errmsg)
          }
        }).catch(err => {
          this.$message.error(err)
        })
      })
    },
    getOrder () {
      let params = `timestamp=${Date.parse(new Date())}&is_first=${this.is_first}`
      // console.log(params)
      this.$getCode(params).then(code => {
        this.http.getMainOrder(code).then(res => {
          if (res.data.errno == '000') {
            // console.log(res)
            this.orderData = res.data.result.data.length > 0 ? res.data.result.data : this.orderData
            // setTimeout(() => {
            // this.intervalTimer = setInterval(() => {
            // setTimeout(() => {
            //   this.shiftOrder()
            // }, 2000)
            // this.orderScroll()
            // this.setMapData()
            // }, 3000)
            // }, 1000)
          } else {
            this.$message.error(res.data.errmsg)
            // this.setMapData()
          }
        }).catch(err => {
          this.$message.error(err)
        })
        this.is_first = 2
      })
    },
    orderScroll (number) {
      let AppScrollTopNow = {
        y: 0
      } // ================================= 定义一个初始位置
      let AppScrollTopEnd = {
        y: -number * 40
      } // ================================= 定义一个结束位置

      // 设置新的缓动动画
      new TWEEN.Tween(AppScrollTopNow) // 传入开始位置
        .to(AppScrollTopEnd, 3000) // 指定时间内完成结束位置
        .easing(TWEEN.Easing.Quadratic.Out) // 缓动方法名
        .onUpdate(() => {
          // 上面的值更新时执行的设置
          this.scrollTop = AppScrollTopNow.y
          // this.scrollTop = AppScrollTopNow.y
          // console.log(AppScrollTopNow.y)
          if (AppScrollTopNow.y === -number * 40 && this.orderData.length > 21) {
            // this.socketData = []
            this.orderTimer = setTimeout(() => {
              this.renderMapData2 = []
            }, 10000)
            for (let index = 0; index < number; index++) {
              this.orderData.shift()
              this.scrollTop = 0
            }
          }
        })
        .start()// ================================= 不要忘了合适的时候启动动画

      // this.orderTimer = setInterval(() => {
      //   if (this.scrollTop * -1 === number * 40) {
      //     this.scrollTop = 0
      //     window.clearInterval(this.orderTimer)
      //     window.clearInterval(this.timer)
      //     this.orderTimer = null
      //     this.timer = null
      //     // this.orderData = []
      //     this.renderMapData2 = []
      //   } else {
      //     this.scrollTop = this.scrollTop - 40
      //   }
      // }, 3000)
    },
    // TweenJs 动画监听
    tweenAni: function () {
      requestAnimationFrame(this.tweenAni)
      TWEEN.update() // ================================= 关键是这句
    },
    ScrollEnd () {
      // location.reload()
      // console.log('ScrollEnd')
      // this.mapIndex = 0
      // window.clearInterval(this.timer)
      // this.timer = null
      // this.orderData = []
      // this.renderMapData2 = []
      // this.getOrder()y
    },
    shiftOrder () {
      // setInterval(() => {
      // this.orderData.shift()
      // }, 5000)
    },
    // getOnline () {
    //   let params = `timestamp=${Date.parse(new Date())}`
    //   this.$getCode(params).then(res => {
    //     this.http.getMainOnline(res).then(res => {
    //       // console.log(res)
    //       if (res.data.errno == '000') {
    //         this.onLine = res.data.result.data
    //         this.percentage = parseFloat(((res.data.result.data.online_count / res.data.result.data.machine_count) * 100).toFixed(3))
    //       } else {
    //         this.$message.error(res.data.errmsg)
    //       }
    //     }).catch(err => {})
    //   }).catch(err => {})
    //   // this.http.getMainOnline(){

    //   // }
    // },
    setMapData () {
      // let fromName = '泉州'
      this.timer = setInterval(() => {
        // if (this.orderData.length === 0) {
        //   window.clearInterval(this.timer)
        //   this.renderMapData2 = []
        //   return false
        // }
        let randomNum = parseInt(Math.random() * 10)
        if ((randomNum === 0 || randomNum === this.renderMapData2.length) && randomNum < this.orderData.length) {
          randomNum = parseInt(Math.random() * 10)
          return randomNum
        }
        console.log('randomNum', randomNum)
        let mapData = []
        if (this.orderData.length > 0) {
          for (let index = 0; index < randomNum; index++) {
            let i = parseInt(Math.random() * this.orderData.length)
            // console.log('orderData', i)
            if (this.orderData[i].longitude !== '' && this.orderData[i].latitude !== '') {
              mapData.push({
                'name': this.orderData[i].location,
                'value': [this.orderData[i].longitude, this.orderData[i].latitude, 19]
              })
            } else {
              mapData.push({
                'name': '',
                'value': ['118.67', '24.88', 19]
              })
            }
          }
          this.renderMapData2 = [...this.socketData, ...mapData]
        }

        setTimeout(() => {
          this.socketData = []
        }, 2000)
        // console.log(randomNum)
        // if (this.mapIndex < this.orderData.length - 1) {
        //   if (this.orderData[this.mapIndex].longitude !== '' && this.orderData[this.mapIndex].latitude !== '') {
        //     this.renderMapData.push({
        //       'fromName': fromName,
        //       'toName': this.orderData[this.mapIndex].region_name,
        //       'value': 19,
        //       'coords': [[118.67, 24.88], [this.orderData[this.mapIndex].longitude, this.orderData[this.mapIndex].latitude]]
        //     })
        //     this.renderMapData2.push({
        //       'name': this.orderData[this.mapIndex].region_name,
        //       'value': [this.orderData[this.mapIndex].longitude, this.orderData[this.mapIndex].latitude, 19]
        //     })
        //   } else {
        //     this.renderMapData.push({
        //       'fromName': fromName,
        //       'toName': fromName,
        //       'value': 19,
        //       'coords': [[118.67, 24.88], ['118.67', '24.88']]
        //     })
        //     this.renderMapData2.push({
        //       'name': '',
        //       'value': ['118.67', '24.88', 19]
        //     })
        //   }
        //   ++this.mapIndex
        // }
      }, 2000)
    },
    initSocket: function () {
      if (typeof (WebSocket) === 'undefined') {
        alert('您的浏览器不支持socket')
      } else {
        // 实例化socket
        this.socket = new ReconnectingWebSocket(this.path)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
        // 发送
        this.socket.onsend = this.send
        // 监听断开
        // this.socket.onclose = this.close
        // 连接建立失败重连
        // this.socket.onerror = this.websocketonerror;
      }
    },
    open: function () {
      this.socket.send(sessionStorage.getItem('id'))
      // console.log(sessionStorage.getItem('id'))
      console.log('socket连接成功')
    },
    error: function () {
      // console.log('error')
      // this.websocketonerror()
      console.log('连接错误')
    },
    websocketonerror () { // 连接建立失败重连
      this.initSocket()
    },
    getMessage: function (msg) {
      // let fromName = '泉州'
      // console.log(msg)

      let data = JSON.parse(msg.data)
      if (data.action === 'newest') {
        this.getOrder()
      }
      if (data.action === 'reload') {
        location.reload()
      }
      console.log('data', data)
      if (data.action) {

      } else {
        this.orderData = [...this.orderData, ...data]
        window.clearTimeout(this.orderTimer)
        this.orderTimer = null
        this.socketData = []
        data.forEach(element => {
          if (element.longitude !== '' && element.latitude !== '') {
            // console.log('element', element)
            this.socketData.push({
              'name': element.location,
              'value': [element.longitude, element.latitude, 19]
            })
            // this.renderMapData2.push({
            //   'name': data.location,
            //   'value': [data.longitude, data.latitude, 19]
            // })
          } else {
            this.socketData.push({
              'name': '福建省泉州市晋江市',
              'value': ['118.67', '24.88', 19]
            })
            // this.renderMapData2.push({
            //   'name': '福建省泉州市晋江市',
            //   'value': ['118.67', '24.88', 19]
            // })
          }
        })
        this.renderMapData2 = this.socketData
        if (this.orderData.length > 21) {
          this.orderScroll(data.length)
        } else {
          this.orderTimer = setTimeout(() => {
            this.renderMapData2 = []
          }, 10000)
        }
        // if (this.orderData.length < 19) {
        //   setTimeout(() => {
        //     // this.socketData = []
        //     this.renderMapData2 = []
        //   }, 3000)
        // }
        // window.clearInterval(this.orderTimer)
        // window.clearInterval(this.timer)
        // this.timer = null
        // this.orderTimer = null
        // this.orderScroll()
        // this.setMapData()
      }
      // if (data.action) {

      // } else {
      //   this.socketData = []
      //   data.forEach(element => {
      //     if (element.longitude !== '' && element.latitude !== '') {
      //       // console.log('element', element)
      //       this.socketData.push({
      //         'name': element.location,
      //         'value': [element.longitude, element.latitude, 19]
      //       })
      //       // this.renderMapData2.push({
      //       //   'name': data.location,
      //       //   'value': [data.longitude, data.latitude, 19]
      //       // })
      //     } else {
      //       this.socketData.push({
      //         'name': '福建省泉州市晋江市',
      //         'value': ['118.67', '24.88', 19]
      //       })
      //       // this.renderMapData2.push({
      //       //   'name': '福建省泉州市晋江市',
      //       //   'value': ['118.67', '24.88', 19]
      //       // })
      //     }
      //   })
      // }
    },
    send: function () {
      setInterval(() => {
        console.log('send', sessionStorage.getItem('id'))
        this.socket.send(sessionStorage.getItem('id'))
      }, 90000)
    },
    close: function () {
      this.socket.close()
      // this.socket = null
      // console.log('close')
      // this.websocketonerror()
      console.log('socket已经关闭')
    }
  },
  destroyed () {
    // 销毁监听
    this.socket.onclose = this.close
  },
  computed: {
    // 公告滚动自定义
    defaultOption () {
      return {
        step: 0.5, // 数值越大速度滚动越快
        limitMoveNum: 2, // 开始无缝滚动的数据量 this.dataList.length
        hoverStop: false, // 是否开启鼠标悬停stop
        direction: 1, // 0向下 1向上 2向左 3向右
        openWatch: true, // 开启数据实时监控刷新dom
        singleHeight: 40, // 单步运动停止的高度(默认值0是无缝不停止的滚动) direction => 0/1
        singleWidth: 0, // 单步运动停止的宽度(默认值0是无缝不停止的滚动) direction => 2/3
        waitTime: 2000, // 单步运动停止的时间(默认值1000ms)
        openTouch: false
      }
    }
  },
  components: {
    // HelloWorld
    MyMaps
  }
}
</script>
<style lang='less'>
.home{
  background: #0b1225;
  display: flex;
  flex-direction: row;
  // padding: 10px ;
  box-sizing: border-box;
  .top-box{
    color: #fff;
    width: 20%;
    height: 100vh;
    // margin: 0 auto;
    padding: 30px 0;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content:flex-end;
    align-items: center;
    .device{
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      // background: linear-gradient(right, #66c4cd, #4392f1);
      border: 1px;
      width: 400px;
      padding: 10px 0;
      .online{
        p{
          text-align: left;
        }
        :first-child{
          font-size: 36px;
          font-weight: bold;
          margin-bottom: 10px;
        }
      }

    }
    .order{
        width: 100%;
        margin-left: 30px;
        height: 100%;
        overflow: hidden;
        position: relative;
        // .seamless-warp{
          // height: 100%;
          // overflow: hidden;
          ul{
            width: 100%;
            position: absolute;
            left: 0;
            li{
              height: 40px;
              border-bottom: 1px dotted #ddd;
              display: flex;
              flex-direction: row;
              justify-content: flex-start;
              align-items: center;
              span{
                display: inline-block;
                overflow: hidden;
                text-overflow:ellipsis;
                white-space: nowrap;
                padding: 0 5px ;
                box-sizing: border-box;
                width: ceil(100%/5);
                text-align: left;
                line-height: 40px;
                font-size: 12px;
              }
              // :first-child{
                // width: 36%;
                // width: 50%;
              // }
            }
          }
        // }
      }
  }
}

</style>
<style>
  .el-progress--circle{
    position: relative;
    margin-left: 30px;
  }
  .el-progress__text{
    position: absolute;
    top: 50%;
    left: 50%;
    color: #fff !important;
    transform: translate(-50%,-50%);
  }
  .el-tooltip__popper {
    padding: 5px 10px;
    border-radius: 5px;
    color: #000;
    background: #fff;
  }
  .seamless-warp div div:last-child{
    display: none !important;
  }
</style>
